<template>
	<el-dialog title="销售库存调整" :visible.sync="isShow" :close-on-click-modal="false" :before-close="close" width="800px">
		<div class="form-box">
			<el-form ref="form" :model="form" :rules="rules" label-width="110px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="商品名称" prop="productName">
							<el-input v-model="item.productName" readonly></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="12">
						<el-form-item label="SKU名称" prop="skuName">
							<el-input v-model="item.skuName" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="当前库存数量" prop="stock">
							<el-input v-model="item.stock" readonly></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="24">
						<el-form-item label="库存调整数量" prop="quantity">
							<el-input type="number" v-model="form.quantity" placeholder="请输入库存调整数量" clearable></el-input>
							<div style="color: #f00;">说明：此处输入的调整数量，将加到原库存数量上；如需减少库存数量，可以输入负数。</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		
		<div slot="footer">
			<el-button type="primary" @click="submit">保 存</el-button>
			<el-button @click="close">取 消</el-button>
		</div>
	</el-dialog>
</template>

<script>
	import { editProductSkuSaleStock } from '@api/product/productSkuSale'
	export default {
		props: {
			isShow: Boolean,
			item: Object,
		},
		data() {
			return {
				form: {
					quantity: '',
				},
				rules: {
					quantity: [{ required: true, message: '请填写需要增加/减少的数量', trigger: 'blur' }],
				},
			}
		},
		methods: {
			submit() {
				this.$refs.form.validate(valid => {
					if (valid) {
						let intRegex = /^-?\d+$/;
						let quantity = Math.abs(this.form.quantity);
						if(!intRegex.test(quantity)) {
							this.$message.error('库存只能输入整数！');
							return;
						}
						if(parseFloat(this.form.quantity) + parseFloat(this.item.stock) < 0) {
							this.$message.error('调整后的库存不能为负数！');
							return;
						}
						
						let params = {
							id: this.item.id,
							quantity: parseFloat(this.form.quantity),
						}
						editProductSkuSaleStock(params)
							.then(() => {
								this.$message.success('库存调整成功！');
								this.close();
								
								this.$emit('submit');
							})
					}
				})
			},
			
			reset() {
				this.$refs.form.resetFields();
			},
			close() {
				this.$emit('close');
				this.reset();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		padding: 20px;
	}
</style>